"ui";
// <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
importClass(android.os.Build);
importClass(android.net.Uri);
importClass(android.os.Environment);
importClass(android.provider.Settings);

//判断是否需要所有文件权限
if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager())) {
  toastLog("已经有这个权限了");
} else {
  toastLog("请授予所有文件访问权限");
  let uri = Uri.parse("package:" + context.getPackageName());
  app.startActivity(Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri));
}



const REQUEST_CODE_FOR_DATA = 666;

selectData();
let storage = storages.create("yashu");
ui.emitter.on("activity_result", (requestCode, resultCode, data) => {
  log(data);
  if (data == null || resultCode != Activity.RESULT_OK) {
    if (requestCode == REQUEST_CODE_FOR_DATA) {
      toastLog("REQUEST_CODE_FOR_DIR refused");
    }
    return;
  }
  if (requestCode == REQUEST_CODE_FOR_DATA) {
    let treeUri = data.getData();
    log("treeUri = " + treeUri); // treeUri = content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata
    storage.put("treeUri", treeUri.toString());
    log("数据存储完成");
  }
});
/* -------------------------------------------------------------------------- */
function selectData() {
  let uri = Uri.parse(getUri("Android%2Fdata"));
  let intent = new Intent("android.intent.action.OPEN_DOCUMENT_TREE");
  intent.putExtra("android.provider.extra.INITIAL_URI", uri);
  log("data: request permission");
  activity.startActivityForResult(intent, 666);
}
function getUri(path) {
  return "content://com.android.externalstorage.documents/tree/primary%3A" + path + "/document/primary%3A" + path;
}